//
//  UiUtil.m
//  Amily
//
//  Created by "" on 15/1/7.
//  Copyright (c) 2015年 Amily. All rights reserved.
//

#import "UiUtil.h"
//#import "DeviceInfo.h"
#import "UIViewExtend.h"
//#import "ALNavigationBar.h"
@implementation UiUtil
CGFloat g_statusBarHeight = 20;
CGSize g_screenSize = CGSizeZero;
+(CGFloat) statusBarHeight {
    return [UiUtil statusBarHeight:[UIApplication sharedApplication].statusBarOrientation];
}

+(CGFloat) statusBarHeight:(UIInterfaceOrientation)orientation {
    // iOS8上的状态栏高度已改成设备方向相关
    CGFloat statusBarHeight = 0;
    if ([UIDevice isPlus]) {
        if (![UIApplication sharedApplication].statusBarHidden) {
            statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
        }
        else {
            // ios8上当statusBar隐藏时，statusBarFrame的宽高为零，取出上一次的结果作为返回值
            statusBarHeight = g_statusBarHeight;
        }
    }
    else {
        if(UIInterfaceOrientationIsLandscape(orientation)) {
            statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.width;
        }
        else {
            statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
        }
    }
    g_statusBarHeight = statusBarHeight;
    return statusBarHeight;
}

+(CGFloat) navigationBarHeightCurOri {
    return [UiUtil navigationBarHeight:[UIApplication sharedApplication].statusBarOrientation];
}

+(CGFloat) navigationBarHeight:(UIInterfaceOrientation)orientation {
    if(UIInterfaceOrientationIsLandscape(orientation)) {
        return  44 ;
    }
    return 44;
}

+(CGFloat) screenHeightCurOri {
    return [UiUtil screenHeight:[UIApplication sharedApplication].statusBarOrientation];
}

+ (CGFloat) screenHeight:(UIInterfaceOrientation)orientation {
    // iOS8上的屏幕大小已改成设备方向相关
    if ([UIDevice isPlus]) {
        if (CGSizeEqualToSize(g_screenSize, CGSizeZero)) {
            // 横竖屏方向不一致，取width作为height
            if((UIInterfaceOrientationIsPortrait(orientation) && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
               || (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) && UIInterfaceOrientationIsLandscape(orientation))) {
                return [[UIScreen mainScreen] bounds].size.width;
            }
            return [[UIScreen mainScreen] bounds].size.height;
        }
        else {
            return g_screenSize.height;
        }
    }
    else {
        if(UIInterfaceOrientationIsLandscape(orientation)) {
            return [[UIScreen mainScreen] bounds].size.width;
        }
        return [[UIScreen mainScreen] bounds].size.height;
    }
}


+(CGFloat) screenWidthCurOri {
    return [UiUtil screenWidth:[UIApplication sharedApplication].statusBarOrientation];
}

+(CGFloat) screenWidth:(UIInterfaceOrientation)orientation
{
    // iOS8上的屏幕大小已改成设备方向相关
    if ([UIDevice isPlus]) {
        if (CGSizeEqualToSize(g_screenSize, CGSizeZero)) {
            // 横竖屏方向不一致，取height作为width
            if((UIInterfaceOrientationIsPortrait(orientation) && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
               || (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) && UIInterfaceOrientationIsLandscape(orientation))) {
                return [[UIScreen mainScreen] bounds].size.height;
            }
            return [[UIScreen mainScreen] bounds].size.width;
        }
        else {
            return g_screenSize.width;
        }
    }
    else {
        if(UIInterfaceOrientationIsLandscape(orientation)) {
            return [[UIScreen mainScreen] bounds].size.height;
        }
        return [[UIScreen mainScreen] bounds].size.width;
    }
}

+(CGSize) screenSizeOri:(UIInterfaceOrientation)orientation
{
    return CGSizeMake([UiUtil screenWidth:orientation],[UiUtil screenHeight:orientation]);
}
#pragma 二级控制器的tabbar的高度
+ (CGFloat)tabBarHeight{
    return 49;
}

//+(CGFloat) visibleHeight:(ALBaseViewController *)controller {
//
//    //整体高度
//    CGFloat fHeight = ALScreenHeightCurOri;
//
//    if (controller.isShowNavigationBar)
//    {
//        fHeight -= BarHeight;
//    }
//    return fHeight;
//}

+ (void)setStatusBarHidden:(BOOL)bHidden withAnimation:(UIStatusBarAnimation)aAnimation {
    
    if( [[UIApplication sharedApplication] respondsToSelector:@selector(setStatusBarHidden:withAnimation:)] ) {
        
        if (aAnimation == UIStatusBarAnimationNone) {
            [[UIApplication sharedApplication] setStatusBarHidden:bHidden] ;
        }
        else {
            [[UIApplication sharedApplication] setStatusBarHidden:bHidden withAnimation:aAnimation];
        }
    } else {
        [[UIApplication sharedApplication] setStatusBarHidden:bHidden] ;
    }
}

+ (BOOL)isStatusBarHidden
{
    return [UIApplication sharedApplication].statusBarHidden;
}

+(NSUInteger) labelNumberOfLines:(NSString *)text maxWidth:(NSInteger)maxWidth font:(UIFont*)font {
    CGFloat lineHeight = [UiUtil labelLineHeight:font];
    CGFloat totleHeight = [UiUtil labelHeight:text maxWidth:maxWidth font:font];
    return (totleHeight + lineHeight - 1) / lineHeight;
}

+(NSUInteger) labelNumberOfLines:(NSString *)text maxWidth:(NSInteger)maxWidth maxHeight:(NSInteger)maxHeight font:(UIFont*)font
{
    CGFloat lineHeight = [UiUtil labelLineHeight:font];
    CGFloat totleHeight = [UiUtil labelHeight:text maxWidth:maxWidth maxHeight:maxHeight font:font];
    return (totleHeight + lineHeight - 1) / lineHeight;
}

+(CGFloat) labelLineHeight:(UIFont*) font {
    return [@"*" sizeWithFont:font].height;
}

+(CGFloat) labelWidth:(NSString *)text  maxWidth:(NSInteger)maxWidth font:(UIFont*)font{
    return [text sizeWithFont:font forWidth:maxWidth lineBreakMode:NSLineBreakByCharWrapping].width;
  
}

+(CGFloat) labelWidth:(NSString*)text font:(UIFont*)font
{
    return [text sizeWithFont:font].width;
}

+(CGFloat) labelHeight:(UILabel *)label
{
    return [UiUtil labelHeight:label.text maxWidth:label.width font:label.font];
}

+(CGFloat) labelHeight:(NSString *) text  maxWidth:(NSInteger)maxWidth  font:(UIFont*)font
{
    return [UiUtil labelHeight:text maxWidth:maxWidth maxHeight:MAXFLOAT font:font];
}

+(CGFloat) labelHeight:(NSString *) text maxWidth:(NSInteger)maxWidth maxHeight:(NSInteger)maxHeight font:(UIFont*)font
{
    if ([text length] == 0) {
        return 0;
    }
//    CGSize expectedLabelSize = [text sizeWithFont:font
//                                constrainedToSize:CGSizeMake(maxWidth, maxHeight)
//                                    lineBreakMode:NSLineBreakByCharWrapping];
    CGSize size =CGSizeMake(maxWidth,maxHeight);
    
    CGSize expectedLabelSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    
    return ceil(expectedLabelSize.height);
    
}

+(NSUInteger) labelWordBreakNumberOfLines:(NSString *)text maxWidth:(NSInteger)maxWidth font:(UIFont*)font {
    CGFloat lineHeight = [UiUtil labelWordBreakHeight:@"*" maxWidth:9999 font:font];
    CGFloat totleHeight = [UiUtil labelWordBreakHeight:text maxWidth:maxWidth font:font];
    return (totleHeight + lineHeight - 1) / lineHeight;
}

+(CGFloat) labelWordBreakWidth:(NSString *)text  maxWidth:(NSInteger)maxWidth font:(UIFont*)font{
    CGSize maximumLabelSize = CGSizeMake(MAXFLOAT,font.lineHeight);
    
      CGSize  expectedLabelSize = [text boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{ NSFontAttributeName:font } context: nil].size;
    
    
    return MIN(maxWidth, expectedLabelSize.width+1);
}
+(CGFloat) labelWordBreakHeight:(NSString *) text  maxWidth:(NSInteger)maxWidth  font:(UIFont*)font{
    if ([text length] == 0) {
        return 0;
    }
    CGSize expectedLabelSize = [text sizeWithFont:font
                                constrainedToSize:CGSizeMake(maxWidth,MAXFLOAT)
                                    lineBreakMode:NSLineBreakByWordWrapping];
    return ceil(expectedLabelSize.height);
}

+(CGSize) labelSizeOfLabel:(UILabel*)label
{
    return [label.text sizeWithFont:label.font];
}

+(CGSize) labelSizeOfLabel:(UILabel*)label maxWidth:(NSInteger)maxWidth
{
    return [label.text sizeWithFont:label.font forWidth:maxWidth lineBreakMode:NSLineBreakByTruncatingTail];
}


// 自动fit一个lable到最小size，位置不变。
+(CGRect) autoFitRectForLable:(UILabel*)lable
{
    CGSize fitSize = lable.frame.size;
    
    CGSize sizeNotContrained = [lable.text sizeWithFont:lable.font];
    
    BOOL isSingleLine =  lable.frame.size.width > sizeNotContrained.width;
    
    if (isSingleLine) {
        fitSize = [lable.text sizeWithFont:lable.font forWidth:lable.frame.size.width lineBreakMode:lable.lineBreakMode];
    }else {
        fitSize = [lable.text sizeWithFont:lable.font constrainedToSize:lable.frame.size lineBreakMode:lable.lineBreakMode];
    }
    
    CGRect newRect = lable.frame;
    
    // x
    switch(lable.textAlignment){
        default:
        case NSTextAlignmentLeft:
        {
            newRect.size.width = fitSize.width;
        }
            break;
        case NSTextAlignmentCenter:
        {
            newRect.origin.x += (newRect.size.width - fitSize.width)/2;
            newRect.size.width = fitSize.width;
        }
            break;
        case NSTextAlignmentRight:
        {
            newRect.origin.x += (newRect.size.width - fitSize.width);
            newRect.size.width = fitSize.width;
        }
            break;
    }
    
    // y
    newRect.origin.y += (newRect.size.height - fitSize.height)/2;
    newRect.size.height = fitSize.height;
    
    return newRect;
}

// 自动fit一个lable到最小size，位置不变。(允许多行)
+(CGRect) autoFitRectForLableAllowMultipleLines:(UILabel*)lable
{
    CGSize fitSize = lable.frame.size;
    
    CGSize sizeNotContrained_OneLine = [lable.text sizeWithFont:lable.font forWidth:9999 lineBreakMode:lable.lineBreakMode];
    CGSize sizeNotContrained_MultipleLine = [lable.text sizeWithFont:lable.font constrainedToSize:CGSizeMake(9999, 9999) lineBreakMode:lable.lineBreakMode];
    
    BOOL isMultipleLine =  sizeNotContrained_MultipleLine.height > sizeNotContrained_OneLine.height * 1.5;
    
    if (isMultipleLine) {
        fitSize = sizeNotContrained_MultipleLine;
    }else {
        fitSize = sizeNotContrained_OneLine;
    }
    
    CGRect newRect = lable.frame;
    
    // x
    switch(lable.textAlignment){
        default:
        case NSTextAlignmentLeft:
        {
            newRect.size.width = fitSize.width;
        }
            break;
        case NSTextAlignmentCenter:
        {
            newRect.origin.x += (newRect.size.width - fitSize.width)/2;
            newRect.size.width = fitSize.width;
        }
            break;
        case NSTextAlignmentRight:
        {
            newRect.origin.x += (newRect.size.width - fitSize.width);
            newRect.size.width = fitSize.width;
        }
            break;
    }
    
    // y
    newRect.origin.y += (newRect.size.height - fitSize.height)/2;
    newRect.size.height = fitSize.height;
    
    return newRect;
}

+ (UIColor*)parseColorFromValues:(NSString *)cssString
{
    
    UIColor* anColor = nil;
    if ([cssString characterAtIndex:0] == '#') {
        unsigned long colorValue = 0;
        float alpha = 1;
        // #FFF
        if ([cssString length] == 4) {
            colorValue = strtol([cssString UTF8String] + 1, nil, 16);
            colorValue = ((colorValue & 0xF00) << 12) | ((colorValue & 0xF00) << 8)
            | ((colorValue & 0xF0) << 8) | ((colorValue & 0xF0) << 4)
            | ((colorValue & 0xF) << 4) | (colorValue & 0xF);
            
            // #FFFFFF
        } else if ([cssString length] == 7) {
            colorValue = strtol([cssString UTF8String] + 1, nil, 16);
        } else if ([cssString length] == 9) {
            alpha = strtol([[cssString substringFromIndex:7] UTF8String],nil,16) / 255.0;
            colorValue = strtol([[cssString substringToIndex:7] UTF8String] + 1, nil, 16);
        }
        
        anColor = RGBACOLOR(((colorValue & 0xFF0000) >> 16),
                            ((colorValue & 0xFF00) >> 8),
                            (colorValue & 0xFF),
                            alpha
                            );
    }
    return anColor;
}
//校验用户手机号码
+ (BOOL) validateUserPhone:(NSString *)str
{
    NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
                                              initWithPattern:@"^1[3|7|4|5|8][0-9][0-9]{8}$"
                                              options:NSRegularExpressionCaseInsensitive
                                              error:nil];
    
    
    
    NSUInteger numberofMatch = [regularexpression numberOfMatchesInString:str
                                                                  options:NSMatchingReportProgress
                                                                    range:NSMakeRange(0, str.length)];
    
    
    if(numberofMatch > 0)
    {
        return YES;
    }
    
    return NO;
    
    
}
//检验邮箱格式
+ (BOOL) validateUserEmail:(NSString *)str
{
    NSRegularExpression * regularexpression = [[NSRegularExpression alloc]
                                               initWithPattern:@"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"
                                               options:NSRegularExpressionCaseInsensitive
                                               error:nil];
    NSUInteger numberofMatch = [regularexpression numberOfMatchesInString:str
                                                                  options:NSMatchingReportProgress
                                                                    range:NSMakeRange(0, str.length)];
    
    if(numberofMatch > 0)
    {
        NSLog(@"%@ isNumbericString: YES", str);
        return YES;
    }
    
    NSLog(@"%@ isNumbericString: NO", str);
    return NO;
}
@end
